package com.ktjiaoyu.crm.service.impl;

import com.ktjiaoyu.crm.entity.Right;
import com.ktjiaoyu.crm.entity.Role;
import com.ktjiaoyu.crm.repository.RightRepository;
import com.ktjiaoyu.crm.repository.RoleRepository;
import com.ktjiaoyu.crm.service.IRoleService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 实现类---角色业务
 * @author Administrator
 */
@Service(value = "roleService")
public class RoleServiceImpl implements IRoleService {
    @Resource
    private RoleRepository roleRepository;

    @Resource
    private RightRepository rightRepository;

    @Override
    public List<Role> findAllRoles() {
        return roleRepository.findAll();
    }

    /**
     * 分页查询
     *
     * @param roleName 角色名称
     * @param pageable 分页条件
     * @return Page<Role>
     */
    @Override
    public Page<Role> findRoles(String roleName, Pageable pageable) {
        Specification<Role> roleSpecification = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (roleName!=null && !roleName.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("roleName"), "%"+roleName+"%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return roleRepository.findAll(roleSpecification, pageable);
    }

    /**
     * 获取所有权限
     *
     * @return 权限
     */
    @Override
    public List<Right> findAllRights() {
        return rightRepository.findAll();
    }

    /**
     * 保存
     *
     * @param role 角色
     * @return 1 or 0
     */
    @Override
    public void saveRole(Role role) {
        roleRepository.save(role);
    }

    /**
     * 获取角色信息
     *
     * @param roleId 角色Id
     * @return 角色
     */
    @Override
    public Role getRole(Long roleId) {
        return roleRepository.findById(roleId).get();
    }

    /**
     * 获取用户-->角色-->权限
     *
     * @param role 角色
     * @return 权限
     */
    @Override
    public List<Right> findRightsByRole(Role role) {
        return rightRepository.findRightsByRoles(role);
    }

    /**
     * 删除角色
     *
     * @param roleId 角色id
     */
    @Override
    public void delRole(Long roleId) {
        //查询该角色的信息
        Role role = roleRepository.getOne(roleId);
        //删除该角色
        roleRepository.delete(role);
    }
}